package com.businesswebsite.businesswebsite.FormalWebExplot.Config;

import com.businesswebsite.businesswebsite.FormalWebExplot.Entity.CompanyUser;
import com.businesswebsite.businesswebsite.FormalWebExplot.Service.User.CompanyUserService;
import com.businesswebsite.businesswebsite.FormalWebExplot.Service.impl.User.CompanyUserImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;


/**
 * @Author: 段美超
 * @CreateTime: 2025-05-20
 * @Description: Rleam工具 shiro框架核心类
 * @Version: 1.0
 */
public class Realm extends AuthorizingRealm {
    @Autowired
    private CompanyUserService companyUserService;

//    用户权限信息结合 负责授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("11111111111111111111111111111111111111111111111111111");
//        获取当前角色信息
        Subject subject = SecurityUtils.getSubject();
        CompanyUser user = (CompanyUser) subject.getPrincipal();
        //设置角色
        Set<String> roles = new HashSet<>();
        roles.add(user.getRole());
        //赋予角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        //赋予权限
        info.addStringPermission(user.getRole());
        System.out.println("权限信息："+info);
        return info;
    }
//    用户角色信息集合 负责登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        创建token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        根据token信息查找对应用户   调用service层的登录方法
        CompanyUser login = companyUserService.Login(token.getUsername(), new String(token.getPassword()));
//        CompanyUser companyUser = companyUserService.SelectByAccount(token.getUsername());
        if(login != null){
//            getName 方法返回当前realm对象的name
            return new SimpleAuthenticationInfo(login,login.getPassword(), getName());
        }
        return null;
    }
}
